<template>
  <div v-if="!showModel">
    <el-space> <el-button type="primary" :icon="Edit" />
      <el-button type="primary" @click="handleCombinClick">合并模型<el-icon class="el-icon--right">
          <Share />
        </el-icon></el-button>
      <el-button type="primary" @click="handleDeleteClick">删除<el-icon class="el-icon--right">
          <Delete />
        </el-icon></el-button>
      <el-button type="primary" :icon="Search">Search</el-button>

      <el-upload v-model:file-list="fileList" class="upload-demo" action="http://10.3.35.13:8086/file/upload"
        :on-preview="handlePreview" :show-file-list="false" :on-remove="handleRemove" :before-remove="beforeRemove"
        accept=".rvt" :on-success="uploadSuccess" :headers="headers" :on-exceed="handleExceed">
        <el-button type="primary">
          上传<el-icon class="el-icon--right">
            <Upload />
          </el-icon>
        </el-button>
        <!-- <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500KB.
          </div>
        </template> -->
      </el-upload></el-space>

    <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="selectable" />
      <el-table-column label="合并模型名称">
        <template #default="scope">{{ scope.row.projectName }}</template>
      </el-table-column>
      <el-table-column property="names" label="模型集" />
      <el-table-column property="localTime" label="创建日期" width="180" />
      <el-table-column fixed="right" label="操作" width="80">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="preview(scope.row.url)">
            预览
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div v-else>
    <el-space> <el-button type="primary" size="large" class="close-btn"
        @click="clickShowModel">关闭</el-button></el-space>
    <iframe class="iframe-model" :src="modelUrl" />
  </div>
  <el-dialog v-model="dialogFormVisible" title="合并模型" width="500">
    <el-form :model="form">
      <el-form-item label="名称：">
        <el-input v-model="form.projectName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述：">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCombinConfirm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { TableInstance, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'
import { get, post, del } from '../server/http.js'
const dialogFormVisible = ref(false);
const showModel = ref(false);
const modelUrl = ref('')
const form = ref({
  projectName: '',
  description: '',
  modelUuids: [],
});
const headers = ref({
  Authorization: `Bearer ${localStorage.getItem("token")}`
});
const tableData = ref(null);
const uploadSuccess = (res) => {
  if (res.code == 0) {
    processData(res.data);
    tableData.value.unshift(res.data)
  }
};
const clickShowModel = () => {
  showModel.value = false;
}
const handleDeleteClick = () => {
  var uuids = []
  var names = ""
  const items = multipleTableRef.value!.getSelectionRows();
  for (let index = 0; index < items.length; index++) {
    const item = items[index];
    uuids.push(item.uuid)
    names += item.projectName + ";"
  }
  ElMessageBox.alert(names, '确认删除？', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (action: Action) => {
      del('/project/delete', uuids).then((res) => {
        if (res.code === 0) {
          ElMessage.success(res.message);
          for (let index = 0; index < items.length; index++) {
            tableData.value = tableData.value.filter((p) => {
              if (p.uuid === items[index].uuid) {
                return false;
              }
              else {
                return true;
              }
            });
          }
        } else {
          ElMessage.error(res.message);
        }
      });
    },
  })

}
const handleCombinConfirm = () => {
  const items = multipleTableRef.value!.getSelectionRows();
  form.value.modelUuids = [];
  for (let index = 0; index < items.length; index++) {
    const item = items[index];
    form.value.modelUuids = [...form.value.modelUuids, ...item.modelUuids];
  }
  post("/project/insert",
    form.value
  ).then((res) => {
    if (res.code === 0) {
      processData(res.data);
      tableData.value.unshift(res.data);
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
    }
  }).catch((err) => {
    console.log(err)
  })
  dialogFormVisible.value = false
}
const preview = (url) => {
  modelUrl.value = url;
  showModel.value = true;
  // window.open(url, "_blank");
}
get("/project/list").then((res) => {
  console.log(res);
  if (res && res.code === 0) {
    tableData.value = res.data;
    tableData.value.forEach(item => {
      processData(item)

    });
  }
}).catch((error) => {
  console.error(error)
})
const processData = (item) => {
  item.names = "";
  item.localTime = formatLocalDate(new Date(item.createdTime));
  item.modelNames.forEach(name => {
    item.names += name + ","
    console.log(item.names);
  });
}
const handleCombinClick = () => {
  dialogFormVisible.value = true;

}
const formatLocalDate = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', { hour12: false });
};
const fileList = ref<UploadUserFile[]>([
  {
    name: 'element-plus-logo.svg',
    url: 'https://element-plus.org/images/element-plus-logo.svg',
  },
  {
    name: 'element-plus-logo2.svg',
    url: 'https://element-plus.org/images/element-plus-logo.svg',
  },
])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])

// const selectable = (row: User) => ![1, 2].includes(row.id)
// const toggleSelection = (rows?: User[], ignoreSelectable?: boolean) => {
//   if (rows) {
//     rows.forEach((row) => {
//       multipleTableRef.value!.toggleRowSelection(
//         row,
//         undefined,
//         ignoreSelectable
//       )
//     })
//   } else {
//     multipleTableRef.value!.clearSelection()
//   }
// }

const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}


</script>
<style scoped>
.close-btn {
  position: absolute;
  /* 绝对定位，相对于容器div#container */
  top: 5%;
  width: 200px;
  /* 按钮垂直居中 */
  left: 50%;
  /* 按钮水平居中 */
  transform: translate(-50%, -50%);
  /* 确保按钮完全居中 */

  z-index: 999;
  /* 确保按钮在 iframe 上面 */

  background-color: rgba(255, 255, 255, 0.3);
  /* 设置透明白色背景，调整最后一个值（alpha）来改变透明度 */
  border: none;
  padding: 10px 20px;
  color: #333;
  /* 文字颜色 */
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  /* 添加悬停效果 */

  backdrop-filter: blur(5px);
  /* 使按钮背景稍微模糊，增强透明效果 */
}

.iframe-model {
  height: 100vh;
  width: 100%;
}
</style>